<template>
    <section class="h-full flex-1 flex flex-col gap-row-4">
        <div class="bg-white box-border">
            <n-form
                :model="queryParameter"
                size="medium"
                ref="queryFromRef"
                label-width="110px"
                label-placement="left"
                require-mark-placement="right-hanging"
                :show-feedback="false"
            >
                <NGrid :x-gap="16" :y-gap="16" cols="12" item-responsive responsive="screen">
                    <NFormItemGi span="12 s:12 m:6 l:6 xl:4 xxl:3" label="登录账号：" path="inputValue">
                        <n-input v-model:value="queryParameter.username" :maxlength="50" clearable placeholder="登录账号" :allow-input="(value) => !value.includes(' ')" />
                    </NFormItemGi>
                    <NFormItemGi span="12 s:12 m:6 l:6 xl:4 xxl:3" label="账号名称：" path="inputValue">
                        <n-input v-model:value="queryParameter.nickname" :maxlength="50" clearable placeholder="账号名称" :allow-input="(value) => !value.includes(' ')" />
                    </NFormItemGi>
                    <NFormItemGi span="12 s:12 m:6 l:6 xl:4 xxl:3">
                        <NSpace class="w-full" justify="end">
                            <NButton @click="deleteData('')" type="error" strong secondary :disabled="keyList.length == 0">批量删除</NButton>
                            <NButton @click="formVisible = true" type="primary">添加用户</NButton>
                            <NButton @click="reset" type="primary" strong secondary>重置</NButton>
                            <NButton @click="query" type="primary">搜索</NButton>
                        </NSpace>
                    </NFormItemGi>
                </NGrid>
            </n-form>
        </div>
        <div class="flex-1 bg-white box-border flex">
            <NDataTable
                class="flex-1 h-full"
                :columns="columnList"
                :data="data"
                :loading="loading"
                :row-key="(row: Data) => row.identity"
                :striped="true"
                :bordered="true"
                :remote="true"
                :flex-height="true"
                :single-line="false"
                :pagination="pagination"
                v-model:checked-row-keys="keyList">
            </NDataTable>
        </div>

        <NModal
            :title="formTitle"
            v-model:show="formVisible"
            :auto-focus="false"
            preset="card"
            :style="{width: '90vw', height: '90vh'}"
            :segmented="{content: 'soft', footer: 'soft'}">
            <select-user v-model:key-list="keyList" />
            <template #footer>
                <NFlex justify="end">
                    <n-button @click="modalCancel">取消</n-button>
                    <n-button @click="modalConfirm" type="primary">确定</n-button>
                </NFlex>
            </template>
        </NModal>

    </section>
</template>

<script setup lang="ts">
import {h, ref} from 'vue'
import {Api} from '@/api/type'
import {RoleApi} from '@/api/role'
import {useTable} from '@/hook/use-table'
import {TableColumn} from 'naive-ui/es/data-table/src/interface'
import SelectUser from '@/view/system/role/function/select-user.vue'
import {NButton, NDataTable, NFlex, NForm, NFormItemGi, NGrid, NInput, NModal, NSpace, NTag, useDialog, useMessage} from 'naive-ui'
// -------------------------------------------------
type R<T> = Api.Common.R<T>;
type Data = Api.System.User;
type PageRecord<T> = Api.Common.PageRecord<T>;
type PageParameter = Api.Common.PageParameter<Data>;
// -------------------------------------------------
const dialog = useDialog()
const message = useMessage()
const roleApi = new RoleApi()
const formTitle = ref<string>('')
const formVisible = ref<boolean>(false)
const keyList = ref<Array<string>>([])

const {identity} = defineProps({
    identity: {
        type: String,
        default: ''
    }
})

const {
    data,
    loading,
    getData,
    columnList,
    pagination,
    queryParameter,
    resetParameter
} = useTable<Data, TableColumn<Data>>({
    queryFn: getPageRecord,
    queryParameter: {
        username: '',
        nickname: ''
    },
    columnList: () => [
        {
            type: 'selection',
            title: '选择列',
            align: 'center',
            titleAlign: 'center',
            width: 48
        },
        {
            title: '登录账号',
            key: 'username',
            align: 'left',
            titleAlign: 'center'
        },
        {
            title: '账号名称',
            key: 'nickname',
            align: 'center',
            titleAlign: 'center'
        },
        {
            title: '手机号',
            key: 'mobile',
            align: 'center',
            titleAlign: 'center'
        },
        {
            title: '是否启用',
            key: 'status',
            align: 'center',
            titleAlign: 'center',
            render(row: Data) {
                return h(NTag, {
                    bordered: false,
                    type: row.status == 1 ? 'info' : 'error'
                }, {default: () => row.status == 1 ? '启用' : '禁用'})
            }
        },
        {
            title: '操作',
            key: 'operate',
            width: '160',
            align: 'center',
            titleAlign: 'center',
            render(row: Data) {
                return h(NSpace, {'justify': 'space-around'}, {
                        default: () => [
                            h(NButton, {onClick: () => deleteData(row.identity), size: 'small', type: 'primary', strong: true, secondary: true}, {default: () => '移除'})
                        ]
                    }
                )
            }
        }
    ] as TableColumn<Data>[]
})

async function reset() {
    resetParameter()
    await getData()
}

async function query() {
    await getData()
}

async function getPageRecord(query: PageParameter): Promise<R<PageRecord<Data>>> {
    query = {
        identity,
        ...query
    }
    let result: R<PageRecord<Data>> = await roleApi.getRoleRelateUser<PageRecord<Data>>(query)
    if (result.code == 0) {
        return result
    } else {
        throw Error(result.message)
    }
}

/**
 * 批量删除数据
 */
async function deleteData(userId: string) {
    if (userId) {
        keyList.value.push(userId)
    }
    if (keyList.value.length == 0) {
        message.error('请先选择数据后再试')
        return
    }
    await new Promise<boolean>((resolve, reject) => {
        dialog.warning({
            title: '提示',
            content: '确定要移除选中的数据吗?',
            positiveText: '确定',
            negativeText: '取消',
            closeOnEsc: false,
            maskClosable: false,
            onPositiveClick() {
                resolve(true)
            },
            onNegativeClick() {
                reject(false)
            }
        })
    }).then(async () => {
        let result: R<PageRecord<Data>> = await roleApi.removeRoleRelateUser(identity, [...keyList.value])
        if (result.code == 0) {
            message.success('移除选中的数据成功')
            await getData()
        } else {
            message.error('移除选中的数据失败' + (result.message || ''))
        }
    }).finally(() => {
        keyList.value = []
    })
}

/**
 * 添加数据
 */
async function insertData() {
    let result = await roleApi.addRoleRelateUser(identity, keyList.value)
    if (result.code == 0) {
        message.success('添加数据成功.')
    } else {
        message.error('添加数据失败.' + (result.message || ''))
    }
}

async function modalCancel() {
    formVisible.value = false
    keyList.value = []
}

async function modalConfirm() {
    formVisible.value = false
    await insertData()
    await getData()
    keyList.value = []
}
</script>
